<template>
  <BasicCard>
    <BasicVxeTable ref="gridRef" v-bind="gridOptions">
      <template #title_right v-if="!isQuYu">
        <span style="margin-left: 15px; font-size: 16px; font-weight: 600">时间：</span>
        <span style="font-size: 16px">{{ titleData.timeString }} {{ titleData.shiftName }}班</span>
        <span style="margin-left: 15px; font-size: 16px; font-weight: 600">班组：</span>
        <span style="font-size: 16px">{{ titleData.teamSet }}组</span>
      </template>

      <template #tools_left>
        <BasicVxeForm
          ref="formRef"
          :formOptions="formOptions"
          :searchLoading="gridOptions.loading"
          @search="getData"
        >
        </BasicVxeForm>
      </template>

      <template #action="{ row }">
        <el-button
          :disabled="tsIdSelect?.startTsId != tsIdSelect?._originalData?.tsId"
          type="primary"
          link
          @click="handleClickEdit(row)"
          >编辑</el-button
        ></template
      >
    </BasicVxeTable>

    <AddForm ref="addForm" :renYuanOptions="renYuanOptions" @success="getData"></AddForm>
  </BasicCard>
</template>

<script setup lang="ts">
  import { clone } from 'xe-utils'
  import dayjs from 'dayjs'
  import { columns, actionColumns, employeeDutySourceMap } from './data'
  import { getListItem, getCurrentAndLastBanCi, getQuYuOptions } from '@/utils'
  import AddForm from './components/AddForm.vue'
  import { getGenGuJianZhiChaXunDuiYingPeiZhi } from '@/api/shengChanJianShi'
  import { GetUserList } from '@/api/persondocument'
  import {
    getRenWuList,
    getRenWuList_qy,
    getHuoQuPaiBanMoShi,
    type GetRenWuListResult
  } from '@/api/personAdmin'

  interface FormV0 {
    quYuValue: string
    tsIdSelect: ShiftSchedulePickerData
  }

  const props = defineProps<{
    gongXuName: string
    gongXuId: string
    isQuYu: boolean
  }>()

  const { t } = useI18n()
  const addForm = ref<InstanceType<typeof AddForm>>()
  const titleData = reactive({
    timeString: '',
    shiftName: '',
    teamSet: ''
  })

  // 人员
  const renYuanOptions = ref<LabelValueOption[]>([])
  // 班次
  const shiftOptions = ref<LabelValueOption[]>([])
  // 区域
  const quYuOptions = ref<LabelValueOption[]>([])

  // 获取排班模式 并加载对应列
  const getPaiBan = async () => {
    await getHuoQuPaiBanMoShi().then(async (res) => {
      if (res != 0) {
        await gridRef.value?.$grid.loadColumn(actionColumns)
      } else {
        await gridRef.value?.$grid.loadColumn(columns)
      }
    })
  }

  // 获取时间列title
  const getTimeColumnTitle = async () => {
    await getGenGuJianZhiChaXunDuiYingPeiZhi('人员排班模式').then((res) => {
      gridRef.value!.$grid!.getColumnByField('scanTime')!.title =
        res.value == '0' ? '记录时间' : '扫码时间'
    })
  }

  //  获取看台人员列表
  const huoQuKanTaiList = () => {
    GetUserList({
      employeeCode: '',
      firstName: '',
      nationId: '',
      gender: 0,
      state: 0,
      // 原来就没有
      jobtitleid: ''
    })
      .then((res) => {
        renYuanOptions.value = res.map((v) => {
          return {
            ...v,
            label: v.firstName,
            value: v.id
          }
        })
      })
      .catch((error) => {
        console.error(error)
      })
  }

  const getData = async () => {
    try {
      const formData = formRef.value!.getFormData()
      const tsIdSelect = formData!.tsIdSelect!

      gridOptions.loading = true

      let res: GetRenWuListResult[]
      if (props.isQuYu) {
        let data = {
          tsid: tsIdSelect.startTsId,
          CraftNodeId: props.gongXuId,
          areaId: formData.quYuValue
        }
        res = await getRenWuList_qy(data)
      } else {
        let data = {
          tsid: tsIdSelect.startTsId,
          CraftNodeId: props.gongXuId,
          // 原来就没有
          jobTitleId: ''
        }
        res = await getRenWuList(data)
      }

      titleData.timeString = tsIdSelect.startTime
      titleData.shiftName = tsIdSelect.startShiftName
      titleData.teamSet = res[0].teamSet

      gridOptions.data = res.map((row) => ({
        ...row,
        scanTime: row.scanTime && dayjs(row.scanTime).format('YYYY-MM-DD'),
        employeeDutySourceStr: getListItem(employeeDutySourceMap, row.employeeDutySource)?.label
      }))
    } catch (err) {
      console.error(err)
    } finally {
      gridOptions.loading = false
    }
  }

  const handleClickEdit = (row) => {
    const data = clone(row, true)

    if (row.personDocumentId != null) {
      data.personDocumentId = row.personDocumentId.split(',')
      if (!row.ratio) {
        data.ciQuanZhongNumber = 1
      } else {
        let quanZhonArr = row.ratio.split(',')
        data.ciQuanZhongNumber = quanZhonArr[0]
        data.ciQuanZhongNumber2 = quanZhonArr[1]
      }
    }

    addForm.value?.openDrawer(true, {
      type: 'edit',
      detail: { ...data, gongXuName: props.gongXuName }
    })
  }

  // 获取tsIdSelect选择器的数据和选项
  const getTsIdSelect = async () => {
    const banCiOpt = await getCurrentAndLastBanCi(
      props.isQuYu ? quYuOptions.value[0].value : props.gongXuId,
      { isQy: props.isQuYu }
    )

    formOptions.data!.tsIdSelect = banCiOpt.banCiInfo
    shiftOptions.value = banCiOpt.shiftOptions
  }

  // 当前选择的tsIdSelect
  const tsIdSelect = computed(() => {
    return formRef.value?.getFormData().tsIdSelect
  })

  const formRef = ref<BasicFormInstance<FormV0>>()
  const formOptions = reactive<BasicFormProps<FormV0>>({
    data: {} as FormV0,
    items: [
      {
        field: 'quYuValue',
        visibleMethod: () => props.isQuYu,
        itemRender: {
          name: 'ElSelect',
          options: computed(() => quYuOptions.value) as unknown as LabelValueOption[],
          events: {
            change: () => {
              // 这是一个由组件注入的自定义方法,可以触发事件
              // params.$form.props.params.executeEvent('search')
              getData()
            }
          }
        }
      },
      {
        field: 'tsIdSelect',
        itemRender: {
          name: 'ShiftSchedulePicker',
          props: {
            showEndShift: false,
            shiftOptions: computed(() => shiftOptions.value) as unknown as LabelValueOption[]
          },
          events: {
            confirm: () => {
              // 这是一个由组件注入的自定义方法,可以触发事件
              // params.$form.props.params.executeEvent('search')
              getData()
            }
          }
        }
      },
      {
        field: 'form-actions',
        itemRender: {
          name: 'ActionButtons',
          children: [{ name: 'search' }]
        }
      }
    ]
  })

  const gridRef = ref<BasicGridInstance>()
  const gridOptions = reactive<BasicGridProps>({
    extraConfig: {
      title: t('pageTitle.机台任务认领'),
      // isCustom: true,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `personAdmin-renWuGuanLi2`, // id用于缓存,务必配置
    height: 'auto',
    loading: false,
    // columns,
    toolbarConfig: {} // 工具栏
  })

  onMounted(async () => {
    await getPaiBan()
    await getTimeColumnTitle()
    // 有区域先拿区域 再用区域选项第一个去拿班次
    if (props.isQuYu) {
      quYuOptions.value = await getQuYuOptions()
      formOptions.data!.quYuValue = quYuOptions.value[0].value
    }
    await getTsIdSelect()

    // 手动查询
    await getData()

    // 最后拿
    await huoQuKanTaiList()
  })
</script>

<style lang="scss" scoped></style>
